<?php
namespace Tbf\Bundle\DatabaseBundle\ListQuery;

use Tbf\Bundle\DatabaseBundle\Exception\DatabaseException;
use Tbf\Bundle\DatabaseBundle\ListQuery\ConditionalExpress\AllLikeConditionalExpress;
use Tbf\Bundle\DatabaseBundle\ListQuery\ConditionalExpress\AndLikeCombineConditionalExpress;
use Tbf\Bundle\DatabaseBundle\ListQuery\ConditionalExpress\InSimpleConditionalExpress;
use Tbf\Bundle\SerializerBundle\Handler\NewFromArray\NewFromArrayInterface;
use Tbf\Bundle\SerializerBundle\Serializer;

class ListQuerySerializer implements NewFromArrayInterface
{
    public function newFromArray($class_name,$input,$group=null)
    {
        $obj = new ListQuery();
        if (!empty($input['page'])) {
            $obj->setPage($input['page']);
        }
        if (!empty($input['page_size'])) {
            $obj->setPageSize($input['page_size']);
        }
        if (!empty($input['orders'])) {
            $obj->setOrder($this->newOrderFromArray($input['orders']));
        }
        if (!empty($input['where'])) {
            $obj->setWhere($this->newWhereFromArray($input['where']));
        }

        return $obj;
    }
    protected function newOrderFromArray($orders)
    {
        $output = array();
        foreach ($orders as $order) {
            $order_obj = new OrderExpress();
            $order_obj->setField($order['field']);
            $order_obj->setDirection($order['direction']);
            $output[] = $order_obj;
        }

        return $output;
    }
    protected function newWhereFromArray($where)
    {
        if ($where['type']==='AndLikeCombineConditionalExpress') {
            return new AndLikeCombineConditionalExpress($where['value']);
        } elseif ($where['type']==='InSimpleConditionalExpress') {
            $obj = new InSimpleConditionalExpress();
            $obj->setField($where['value']['field']);
            $obj->setValue($where['value']['value']);

            return $obj;
        } elseif ($where['type']==='AllLikeConditionalExpress') {
            return new AllLikeConditionalExpress($where['value']);
        }
        throw new DatabaseException('do not understand type:'.$where['type']);
    }
}
